package com.tongqin.distributed.vip;

import com.mysql.jdbc.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author yuantongqin
 * @date 2018/8/31 上午10:30
 */
public class GPExecutorImpl implements GPExecutor {

    /**
     * 这里就是真正连接数据库进行数据库的查询操作
     * @param statement
     * @param params
     * @param <T>
     * @return
     */
    @Override
    public <T> T query(String statement, String params) {
        Connection connection = null;
        Test test = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName(" com.mysql.jdbc.Driver");
            connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/gupao?useSSL=false&zeroDateTimeBehavior=convertToNull&characterEncoding=utf8");
            String sql = String.format(statement,params);
            preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                test = new Test();
                test.setId( resultSet.getInt(1));
                test.setName(resultSet.getString(3));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return (T) test;
    }
}
